//
//  SportDetailViewController.m
//  StormWatch
//
//  Created by 王岩 on 2024/9/14.
//

#import "SportDetailViewController.h"
#import "SportDetailCell.h"
#import "SportRecordTable+CoreDataClass.h"
#import "SportDetailModel.h"
#import "SportDetailListHeaderView.h"

@interface SportDetailViewController ()
/* <#note#> */
@property (nonatomic, strong) NSMutableDictionary<NSString *, NSMutableArray *> * dateDic;
@end

@implementation SportDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = SWString(@"History");
    
    // Do any additional setup after loading the view.
}

- (void)initData {
    NSManagedObjectContext * context = [[DBManager sharedManager] managedObjectContext];

    NSFetchRequest *  request = [[NSFetchRequest alloc] initWithEntityName:@"SportRecordTable"];
    NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey:@"startTime" ascending:NO];
    request.sortDescriptors = @[sort];
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"deviceUUID = %@ && sportType = %ld",[FRQBluetoothManager shareManager].uuid, [self getSportTypeValue]];
    request.predicate = predicate;
    NSArray<SportRecordTable *> * result = [context executeFetchRequest:request error:nil];
    
    for (int i = 0; i < result.count; i ++) {
        SportRecordTable * sr = result[i];
        SportDetailModel * model = [[SportDetailModel alloc] init];
        model.name = self.name;
        model.stepValue = sr.sportStep;
        model.rateValue = sr.sportRate;
        model.distanceValue = sr.sportDistance;
        model.sportTime = sr.sportTime;
        model.timeHMSStr = sr.timeHMS;
        model.timeYMDStr = sr.timeYMD;
        model.caloValue = sr.sportCalo;
        model.startTime = sr.startTime;
        
        if ([self.dateDic.allKeys containsObject:model.timeYMDStr]) {
            NSMutableArray * arr = [self.dateDic valueForKey:model.timeYMDStr];
            [arr addObject:model];
        }else {
            NSMutableArray * arr = [[NSMutableArray alloc] init];
            [arr addObject:model];
            [self.dateDic setValue:arr forKey:model.timeYMDStr];
            [self.dataArr addObject:arr];
        }
        
    }

    [self.tableView reloadData];
}

- (void)initUI {
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavigationBarHeight - kHomeIndicatorHeight);
    [self.tableView registerNib:[UINib nibWithNibName:@"SportDetailCell" bundle:nil] forCellReuseIdentifier:@"SportDetailCell"];
    [self.tableView registerClass:[SportDetailListHeaderView class] forHeaderFooterViewReuseIdentifier:@"SportDetailListHeaderView"];
    self.tableView.separatorInset = UIEdgeInsetsZero;
    [self.view addSubview:self.tableView];
    [self readData];
}

- (void)readData {
    
    [[StormCommandTool sharedInstance] readSportData:^(BOOL success, NSArray<NSArray *> * _Nonnull allData) {
        if (success) {
            NSManagedObjectContext * context = [[DBManager sharedManager] managedObjectContext];

            for (int i = 0; i < allData.count; i ++) {
                SportDetailModel * model = [SportDetailModel creatModelWithInfo:allData[i]];
                model.name = self.name;
                if (model.type != [self getSportTypeValue]) {
                    continue;
                }
                
                ///  更新数据库
                NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"SportRecordTable"];
                NSPredicate * predicate = [NSPredicate predicateWithFormat:@"startTime == %lld && deviceUUID = %@ && sportType = %d",model.startTime, [FRQBluetoothManager shareManager].uuid, [self getSportTypeValue]];
                request.predicate = predicate;
                NSArray<SportRecordTable *> *result = [context executeFetchRequest:request error:nil];
                if (result.count > 0) {
                    continue;;
                }else {
                    SportRecordTable * sr = [NSEntityDescription insertNewObjectForEntityForName:@"SportRecordTable" inManagedObjectContext:context];
                    sr.sportStep = model.stepValue;
                    sr.sportRate = model.rateValue;
                    sr.sportDistance = model.distanceValue;
                    sr.sportTime = model.sportTime;
                    sr.timeHMS = model.timeHMSStr;
                    sr.timeYMD = model.timeYMDStr;
                    sr.sportCalo = model.caloValue;
                    sr.startTime =  model.startTime;
                    sr.sportType = [self getSportTypeValue];
                    sr.deviceUUID = [FRQBluetoothManager shareManager].uuid;
                }
                [[DBManager sharedManager] saveContext];
                
                if ([self.dateDic.allKeys containsObject:model.timeYMDStr]) {
                    NSMutableArray * arr = [self.dateDic valueForKey:model.timeYMDStr];
                    [arr insertObject:model atIndex:0];
                }else {
                    NSMutableArray * arr = [[NSMutableArray alloc] init];
                    [arr addObject:model];
                    [self.dateDic setValue:arr forKey:model.timeYMDStr];
                    [self.dataArr insertObject:arr atIndex:0];
                }
                
            }
            
            [self.tableView reloadData];
            
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray * arr = self.dataArr[section];
    return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SportDetailCell * cell = [tableView dequeueReusableCellWithIdentifier:@"SportDetailCell" forIndexPath:indexPath];
    cell.model = self.dataArr[indexPath.section][indexPath.row];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SportDetailListHeaderView * view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SportDetailListHeaderView"];
    
    NSArray * arr = self.dataArr[section];
    SportDetailModel * m = arr.firstObject;
    view.dateLab.text = m.timeYMDStr;
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120.;
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:self.noDataImageName];
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = [NSString stringWithFormat:@"%@ %@ %@",SWString(@"No"), self.name, SWString(@"data")];
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:15.0f],
                                 NSForegroundColorAttributeName: kUIColorFromRGB(0xaaaaaa)};
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -50;
}
- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView
{
    return 10.0f;
}



- (int)getSportTypeValue{
    switch (self.type) {
        case SportType_Running:
            return 2;
            break;
        case SportType_Riding:
            return 3;
            break;
        case SportType_Tennis:
            return 8;
            break;
        case SportType_Climbing:
            return 9;
            break;
        case SportType_Walking:
            return 10;
            break;
        case SportType_Basketball:
            return 11;
            break;
        case SportType_Soccer:
            return 12;
            break;
        case SportType_Yoga:
            return 20;
            break;
        case SportType_Workout:
            return 26;
            break;
        default:
            break;
    }
    return 0;
}



- (NSMutableDictionary<NSString *,NSMutableArray *> *)dateDic{
    if (!_dateDic) {
        _dateDic = [[NSMutableDictionary alloc] init];
    }
    return _dateDic;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
